//
//  Utils.m
//  oschina_song
//
//  Created by song on 16/1/31.
//  Copyright © 2016年 song. All rights reserved.
//

#import "Utils.h"
#import "GRMustache.h"
#import "TOWebViewController.h"

@implementation Utils


+(MBProgressHUD*)createHUD
{
    UIWindow *window =[[UIApplication sharedApplication].windows lastObject];
    MBProgressHUD *HUD =[[MBProgressHUD alloc] initWithWindow:window];
    HUD.detailsLabelFont  = [UIFont boldSystemFontOfSize:16];
    [window addSubview:HUD];
    [HUD show:YES];
    HUD.removeFromSuperViewOnHide = YES;
    return  HUD;
}

+(NSString *)htmlWithData:(NSDictionary *)data usingTemple:(NSString *)templeName
{
    NSString *templePath = [[NSBundle mainBundle] pathForResource:templeName ofType:@"html" inDirectory:@"html"];
  
    
    NSString *temple = [NSString stringWithContentsOfFile:templePath encoding:NSUTF8StringEncoding error:nil];
    
    NSMutableDictionary *mdata = [data mutableCopy];
    
    return [GRMustacheTemplate renderObject:mdata fromString:temple error:nil];
}



+(void)analysis:(NSString *)url andNavController:(UINavigationController *)navVC
{
    NSRange range = [url rangeOfString:@"oschina.net"];
    
    if(range.length <=0)
    {
        url = [ url hasPrefix:@"http://"] ? url :[NSString stringWithFormat:@"http://%@",url];
        TOWebViewController *webViewController = [[TOWebViewController alloc] initWithURLString:url];
        webViewController.hidesBottomBarWhenPushed = YES;
        [navVC pushViewController:webViewController animated:YES];
        
    }
}

+(UIImage *)createQRCodeFromString:(NSString *)str
{
    NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    CIFilter *QRFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [QRFilter setValue:stringData forKey:@"inputMessage"];
    [QRFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    
    CGFloat scale = 5;
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:QRFilter.outputImage fromRect:QRFilter.outputImage.extent];
    
    //Scale the image usign CoreGraphics
    CGFloat width = QRFilter.outputImage.extent.size.width * scale;
    UIGraphicsBeginImageContext(CGSizeMake(width, width));
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    //Cleaning up
    UIGraphicsEndImageContext();
    CGImageRelease(cgImage);
    
    return image;
}



@end
